package com.ironman.compute;

import cn.hutool.core.util.StrUtil;
import com.ironman.compute.generator.ComputeDataGenerator;
import com.ironman.event.properties.SysTrainingProperties;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.codec.MqttQoS;
import net.dreamlu.iot.mqtt.core.client.MqttClient;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.BiConsumer;

@Slf4j
@Component
public class ComputeDataFactory {

    @Resource
    MqttClient mqttClient;

    @Resource
    SysTrainingProperties sysTrainingProperties;

    @Resource
    List<ComputeDataGenerator> computeDataGenerators;

    @PostConstruct
    public void init() {
        for (ComputeDataGenerator computeDataGenerator : computeDataGenerators) {
            computeDataGenerator.start(sysTrainingProperties.getMHmId(), new BiConsumer<String, String>() {
                @Override
                public void accept(String topicType, String computeData) {
                    String topic = StrUtil.format("mobile/up/{}/{}/{}/{}", topicType, sysTrainingProperties.getTenantCode(), sysTrainingProperties.getLeveId(), sysTrainingProperties.getMHmId());
                    boolean published = mqttClient.publish(topic, computeData.getBytes(StandardCharsets.UTF_8), MqttQoS.valueOf(1));
                    log.info("Compute data: {}  published {}", computeData, published);
                }
            });
        }
    }

}
